<template>
  <div class="container">
    <el-card>
      <template #header>
        {{ biaoti }}
      </template>
      <el-form
        :model="formInline"
        :rules="rules"
        status-icon
        ref="form"
        label-width="150px"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            v-model="formInline.subjectID"
            placeholder="请选择"
            @focus="getSubjectsList"
            @change="getcatalogID"
          >
            <el-option
              v-for="item in subjectsListData"
              :key="item.value"
              :label="item.label"
              :value="{ label: item.label, value: item.value }"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="formInline.catalogID" placeholder="请选择">
            <el-option
              v-for="item in catalogIDList"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业：" prop="enterpriseID">
          <el-select
            @focus="getenterpriseID"
            v-model="formInline.enterpriseID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in enterpriseIDList"
              :key="item.id"
              :label="item.shortName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市：" prop="city">
          <!-- 市区的选择 -->
          <el-select
            @change="provinceChange"
            v-model="formInline.province"
            placeholder="请选择"
            class="province"
          >
            <el-option
              v-for="item in provinceList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <!-- 城市区域的选择 -->
          <el-select
            v-model="formInline.city"
            placeholder="请选择"
            class="county"
          >
            <el-option
              v-for="item in areas"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="方向：" prop="direction">
          <el-select v-model="formInline.direction" placeholder="请选择">
            <el-option
              v-for="item in direction"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="form.questionType" fill="#17203a">
            <el-radio label="单选"></el-radio>
            <el-radio label="多选"></el-radio>
            <el-radio label="简答"></el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- ========================================= -->

        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="formInline.questionType" fill="#17203a">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- -============================================================= -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="formInline.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="题干：" prop="question">
          <QuillEditor
            ref="QuillEditor_question"
            :question.sync="formInline.question"
            @onEditorBlur="handle_onEditorBlur"
          ></QuillEditor>
        </el-form-item>
        <!-- 单选 -->
        <el-form-item
          v-if="this.formInline.questionType === '1'"
          label="选项："
          prop="questionTypes"
        >
          <el-row
            v-for="(item, index) in choice"
            :key="item"
            type="flex"
            justify="start"
            align="middle"
            class="radio"
          >
            <el-col :span="6">
              <el-radio :label="item" v-model="isRight">{{ item }} : </el-radio>
              <el-input v-model="title[index]"></el-input>
            </el-col>
            <el-col :span="6">
              <ImageUpload :ref="item"></ImageUpload>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 复选框 -->
        <el-form-item
          v-if="this.formInline.questionType === '2'"
          label="选项："
          prop="questionTypes"
          ><el-checkbox-group v-model="checklist">
            <el-row
              v-for="(item, index) in choice"
              :key="item"
              type="flex"
              justify="start"
              align="middle"
              class="radio"
            >
              <el-col :span="6">
                <el-checkbox :label="item">{{ item }} : &nbsp;</el-checkbox>
                <el-input v-model="title[index]"></el-input
              ></el-col>
              <el-col :span="6"><ImageUpload :ref="item"></ImageUpload></el-col>
            </el-row>
          </el-checkbox-group>
        </el-form-item>

        <!-- ==================================== -->

        <!-- ======================== -->
        <el-form-item>
          <el-button
            ref="addBtn"
            type="danger"
            @click="addBtn"
            v-if="this.formInline.questionType !== '3'"
            :disabled="this.formInline.questionType !== '2'"
            ><i class="el-icon-plus"></i> 增加选项与答案</el-button
          >
        </el-form-item>

        <el-form-item label="解析视频:">
          <el-input
            v-model="formInline.videoURL"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <el-form-item label="答案解析:" prop="answer">
          <QuillEditor
            ref="QuillEditor_answer"
            :answer.sync="formInline.answer"
            @onEditorBlur="handle_onEditorBlur"
          ></QuillEditor>
        </el-form-item>

        <el-form-item label="题目备注：" prop="remarks">
          <el-input
            type="textarea"
            v-model="formInline.remarks"
            style="width: 500px"
            :rows="5"
          ></el-input>
        </el-form-item>

        <el-form-item label="试题标签：" prop="tags">
          <el-select
            v-model="formInline.tags"
            multiple
            placeholder="请选择试题标签"
            style="width: 500px"
          >
            <el-option
              v-for="item in tagList"
              :key="item.id"
              :label="item.tagName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit" v-if="biaoti === '试题录入'"
            >确定提交</el-button
          >
          <el-button type="danger" @click="submit" v-if="biaoti === '试题修改'"
            >确定修改</el-button
          >
          <!-- <el-button type="danger" @click="test">测试</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import VueQuillEditor from "@/components/VueQuillEditor/VueQuillEditor.vue";
import {
  subjectsList,
  directionList,
  tagsList,
  getCompanysList,
  getQuestionDetail,
  addQuestions,
} from "@/api/hmmm/questions";
import ImageUpload from "@/components/ImageUpload/index";

import { provinces, citys } from "@/api/hmmm/citys.js";
import { direction } from "@/api/hmmm/constants";
// import { rawListeners } from 'process'
export default {
  name: "QuestionsNew",
  components: {
    QuillEditor: VueQuillEditor,
    ImageUpload,
  },
  data() {
    return {
      // 多选选中数组
      checklist: [],
      formInline: {
        subjectID: "", // 学科
        catalogID: "", // 二级目录
        enterpriseID: "", // 企业
        tags: "", // 标签
        keyword: "", // 关键字
        questionType: "1", // 试题类型
        difficulty: "", // 难度
        direction: "", // 方向
        creatorID: "2", // 录入人
        remarks: "", // 题目备注
        province: "", // 城市
        city: "", // 城市下管的市区
        options: [], // 答案
        videoURL: "", // 视频地址
        answer: "", // 答案解析
        question: "", // 题干
      },
      // 选项数据
      optionsData: {
        code: "",
        title: "",
        img: "",
        isRight: "",
      },
      // 城市及地区列表
      provinceList: [],
      areas: [],
      // 方向数据
      direction,
      // 学科 标签以及二级目录数据
      subjectsListData: [],
      catalogIDList: [],
      tagList: [],
      // 企业
      enterpriseIDList: [],
      // 选项数组
      choice: ["A", "B", "C", "D"],
      count: 68,
      editimgURL: [],
      // 校验
      rules: {
        subjectID: [
          { required: true, message: "请输入学科", trigger: "change" },
        ],
        catalogID: [
          { required: true, message: "请输入目录", trigger: "change" },
        ],
        enterpriseID: [
          { required: true, message: "请输入企业", trigger: "change" },
        ],
        province: [
          { required: true, message: "请输入城市", trigger: "change" },
        ],
        city: [{ required: true, message: "请输入地区", trigger: "change" }],
        direction: [
          { required: true, message: "请输入方向", trigger: "change" },
        ],
        questionType: [
          { required: true, message: "请输入题型", trigger: "change" },
        ],
        difficulty: [
          { required: true, message: "请输入难度", trigger: "change" },
        ],
        question: [
          { required: true, message: "请输入题干", trigger: "change" },
        ],
        answer: [
          { required: true, message: "请输入答案解析", trigger: "change" },
        ],
        remarks: [
          { required: true, message: "请输入题目备注", trigger: "change" },
        ],
        tags: [
          { required: true, message: "请输入试题标签", trigger: "change" },
        ],
      },
      checked: true,
      isRight: "A",
      title: ["A", "B", "C", "D"],
      biaoti: "试题录入",
    };
  },
  created() {
    // 获取所有城市的列表
    this.getprovinceList();
    this.judgment();
  },

  methods: {
    // 获取所有城市的列表
    getprovinceList() {
      this.provinceList = provinces();
    },
    // 当城市列表下拉框发生变化时
    provinceChange(data) {
      this.formInline.city = "";
      this.province = data;
      this.areas = citys(data);
      this.formInline.province = data;
    },
    // 获取学科列表
    async getSubjectsList(val) {
      const { data } = await subjectsList();
      this.subjectsListData = data;
      // console.log('整个学科列表')
      // console.log(data)
    },
    // 当学科发生变化时获取整个二级目录列表，与学科进行比对分配,标签也是与学科进行绑定
    async getcatalogID(val) {
      const {
        data: { items },
      } = await directionList({ page: 1, pagesize: 200 });
      this.SubjectID = val.value;
      this.catalogIDList = items.filter((item) => {
        return item.subjectName === val.label;
      });
      this.gettagsList(val);
    },
    // 获取所有的标签列表,并与学科进行绑定判断
    async gettagsList(val) {
      const {
        data: { items },
      } = await tagsList({ page: 1, pagesize: 200 });
      // console.log(items)
      this.tagList = items.filter((item) => {
        return item.subjectName === val.label;
      });
    },
    // 学科 目录 标签 三个下拉框部分完成
    // 获取企业列表
    async getenterpriseID() {
      const {
        data: { items },
      } = await getCompanysList({ page: 1, pagesize: 100 });
      this.enterpriseIDList = items;
    },
    // 选项内部的数据是需要根据数组长度进行定义的
    setOptionsData() {
      for (let i = 0; i < this.choice.length; i++) {
        this.formInline.options[i] = { ...this.optionsData };
        this.formInline.options[i].code = this.choice[i];
        this.formInline.options[i].title = this.title[i];
      }
    },
    // 最后提交按钮
    async submit() {
      this.setRadioData();
      // console.log(this.formInline)
      this.formInline.subjectID = this.formInline.subjectID.value;
      await addQuestions(this.formInline);
      // console.log(res)
      this.$router.push({
        path: "/questions/list",
        query: { state: this.biaoti },
      });
    },
    // 当修改时生成一个数组存放 A B C D,根据返回的数据
    createChoiceArr(count) {
      this.choice = [];
      for (let i = 65; i < 65 + count; i++) {
        this.choice.push(String.fromCharCode(i));
      }
    },
    // 增加选项
    addBtn() {
      this.count++;
      this.choice.push(String.fromCharCode(this.count));
      this.title.push("");
    },
    // 判断是新增还是修改
    async judgment() {
      if (this.$route.query.id) {
        this.biaoti = "试题修改";
        // 获取试题具体数据
        const res = await getQuestionDetail(this.$route.query.id);
        this.formInline = res.data;
        // console.log(this.formInline)
        this.$refs.QuillEditor_question.init(res.data.question);
        this.$refs.QuillEditor_answer.init(res.data.answer);

        // 不是简答题时
        if (this.formInline.questionType !== "3") {
          // 计算出选项长度
          this.createChoiceArr(this.formInline.options.length);
          // 选项数据框渲染出来
          this.title = this.formInline.options.map((item) => {
            return item.title;
          });
          this.formInline.options.forEach((item, index) => {
            if (item.isRight === 1) this.isRight = this.choice[index];
          });
          this.editimgURL = this.formInline.options.map((item) => {
            return item?.img;
          });
          // console.log(this.editimgURL)
          this.setImgDomUrl();
        }
      } else {
        this.formInline = {
          subjectID: "", // 学科
          catalogID: "", // 二级目录
          enterpriseID: "", // 企业
          tags: "", // 标签
          keyword: "", // 关键字
          questionType: "1", // 试题类型
          difficulty: "", // 难度
          direction: "", // 方向
          creatorID: "", // 录入人
          remarks: "", // 题目备注
          province: "", // 城市
          city: "", // 城市下管的市区
          options: [], // 答案
          videoURL: "", // 视频地址
          answer: "", // 答案解析
          question: "", // 题干
        };
      }
    },
    // 提交时选择数据的给予
    setRadioData() {
      // 首先根据当前的选项长度写出 options
      this.setOptionsData();
      this.imgURL();
      // 单选
      if (this.formInline.questionType === "1") {
        this.formInline.options.forEach((item) => {
          if (item.code === this.isRight) {
            item.isRight = 1;
          } else {
            item.isRight = 0;
          }
        });
      }
      // 多选
      if (this.formInline.questionType === "2") {
        // console.log(this.checklist.includes('A'))
        this.formInline.options.forEach((item) => {
          if (this.checklist.includes(item.code)) {
            item.isRight = 1;
          } else {
            item.isRight = 0;
          }
        });
      }

      // console.log(this.formInline.options)
    },
    // 富文本失去焦点时
    async handle_onEditorBlur() {
      await this.$refs.form.validateField("question");
      await this.$refs.form.validateField("answer");
    },
    // 将图片地址添加进上传的数据
    imgURL() {
      const res = this.choice.map((item) => {
        return this.$refs[item][0].fileList[0]?.url;
      });
      res.map((item, index) => {
        this.formInline.options[index].img = item || "";
      });
    },
    // 将图片地址传递进生成的dom中
    setImgDomUrl() {
      this.choice.map((item, index) => {
        const url = this.editimgURL[index];
        if (url !== "") {
          this.$refs[item][0].fileList = [{ url, upload: true }];
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.el-card {
  margin: 25px;
  .el-form {
    .el-form-item {
      .el-select {
        width: 450px;
      }
      .province {
        width: 225px;
      }
      .county {
        width: 225px;
      }
    }
  }
}
.el-col {
  .el-input {
    width: 70%;
  }
}
.radio {
  margin-bottom: 15px;
}
.el-upload--picture-card {
  width: 80px;
  height: 80px;
  background: red;
}
</style>
